import { app, shell, BrowserWindow } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import store from './store'
import init from './perference'
import './events'

function createWindow(): void {
	const mainWindow = new BrowserWindow({
		width: 1300,
		height: 800,
		show: false,
		autoHideMenuBar: true,
		webPreferences: {
			preload: join(__dirname, '../preload/index.js'),
			sandbox: false
		}
	})

	mainWindow.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
			// google 会检测该请求头,跨域会返回403
			delete details.requestHeaders['Sec-Fetch-Site']
			callback({ requestHeaders: { Origin: '*', ...details.requestHeaders } });
		},
	);

	mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
		callback({
			responseHeaders: {
				'Access-Control-Allow-Origin': ['*'],
				'Access-Control-Allow-Headers': ['Content-Type'],
				...details.responseHeaders
			}
		})
	})

	mainWindow.on('ready-to-show', () => {
		mainWindow.show()
	})

	mainWindow.webContents.setWindowOpenHandler((details) => {
		shell.openExternal(details.url).then(_ => { })
		return { action: 'deny' }
	})

	if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
		mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']).then(_ => { })
	} else {
		mainWindow.loadFile(join(__dirname, '../renderer/index.html')).then(_ => { })
	}
}


app.whenReady().then(() => {

	electronApp.setAppUserModelId('com.zhongjiannan')
	createWindow()

	init(store)

	app.on('browser-window-created', (_, window) => {
		optimizer.watchWindowShortcuts(window)
	})

	app.on('activate', function () {
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
})

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') app.quit()
})